package org.zhangyp.n02datastructure.n01Array;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author ypzhang
 * @since 2024/12/20
 */
public class Test {
    public int[] twoSum(int[] nums, int target) {
        int[] indexs = new int[2];
        Map<Integer, Integer> exist = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int x = target - nums[i];
            if (exist.containsKey(x)) {
                indexs[0] = exist.get(x);
                indexs[1] = i;
                return indexs;
            } else {
                exist.put(nums[i], i);
            }
        }
        return indexs;
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l1Cur = l1;
        ListNode l2Cur = l2;

        ListNode head = null;
        ListNode pre = null;
        int nextAdd = 0;
        while (l1Cur != null || l2Cur != null || nextAdd > 0) {
            int curVal = nextAdd;
            if (l1Cur != null) {
                curVal += l1Cur.val;
                l1Cur = l1Cur.next;
            }
            if (l2Cur != null) {
                curVal += l2Cur.val;
                l2Cur = l2Cur.next;
            }
            if (curVal > 9) {
                curVal = curVal - 10;
                nextAdd = 1;
            } else {
                nextAdd = 0;
            }
            if (pre == null) {
                pre = new ListNode(curVal);
                head = pre;
            } else {
                pre.next = new ListNode(curVal);
                pre = pre.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        int[] arr1 = {9,9,9,9,9,9,9};
        int[] arr2 = {9,9,9,9};
        ListNode l1 = arrayToListNode(arr1);
        ListNode l2 = arrayToListNode(arr2);
        ListNode result = addTwoNumbers(l1,l2);
        System.out.println(result);
    }

    public static ListNode arrayToListNode(int[] arr){
        ListNode l1 = new ListNode(arr[0]);
        ListNode cur = l1;
        for(int i = 1; i < arr.length;i++){
            cur.next = new ListNode(arr[i]);
            cur = cur.next;
        }
        return l1;
    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return  val + ", " + next ;
        }
    }
}
